package com.cc.visitor.service;

import com.cc.visitor.dao.JssdkSignatureMapper;
import com.cc.visitor.entity.JsapiTicket;
import com.cc.visitor.entity.wechat.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author chanchaw
 * @create 2025-01-19 8:17
 */
@Service
public class JssdkSignatureServiceImpl implements JssdkSignatureService{
    @Autowired
    private JsapiTicketService jsapiTicketService;

    /**
     * 原本计划每次生成的 signature 都记录进入DB
     * 后来放弃写入，只返回给调用者
     * @param url
     * @return
     */
    @Override
    public Signature getSignature(String url) {
        String noncestr = "chanchaw";
        String timestamp = String.valueOf(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        JsapiTicket activeTicket = jsapiTicketService.getActiveTicket();
        String ticket = activeTicket.getTicket();

        // 移除url中#之后的所有字符串
        int i = url.indexOf("#");
        String activeUrl = "";
        if(i < 0) activeUrl = url;
        else url.substring(0, i);

        String sigString = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + activeUrl;
        String signature = sha1(sigString);
        return Signature.builder().nonceStr(noncestr).timestamp(timestamp).signature(signature).build();
    }

    private static String sha1(String src) {
        try {
            MessageDigest md = MessageDigest.getInstance("sha1");
            byte[] digest = md.digest(src.getBytes());
            char[] chars = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };

            StringBuilder sb = new StringBuilder();
            for( byte b:digest ) {
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        }
        return null;
    }
}
